package tt.dz.service.imp.sys;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import tt.dz.base.authentication.entity.LoginParam;
import tt.dz.base.authentication.entity.RPCLoginRes;
import tt.dz.base.authentication.service.AuthenService;
import tt.dz.base.common.entity.ApiResult;
import tt.dz.dao.base.BaseDao;
import tt.dz.dao.ext.charger.OmsChargerDao;
import tt.dz.dao.ext.station.OmsStationDao;
import tt.dz.dao.ext.system.OmsOperListDao;
import tt.dz.entity.base.JsonCommon;
import tt.dz.entity.base.JsonForList;
import tt.dz.entity.charger.OmsCharger;
import tt.dz.entity.station.OmsStation;
import tt.dz.entity.station.OmsStationLocation;
import tt.dz.entity.system.OmsOperList;
import tt.dz.service.imp.base.BaseService;
import tt.dz.service.sys.EnterpriseService;
import tt.dz.service.sys.StationService;
import tt.dz.tcp.rpc.ms.SystemMasterServerRpcClient;
import tt.dz.tcp.rpc.ms.client.entity.MasterQueryCardsVO.MasterQueryCardsParamVO;
import tt.dz.tcp.rpc.ms.client.entity.MasterQueryCardsVO.MasterQueryCardsRetVO;
import tt.dz.util.OmsConstant.MsgCodeEnum;
import tt.dz.vo.oms.OmsStationVO;
import tt.dz.util.StringUtil;
import tt.dz.util.serialGenerater;
/**
 * enterpriselogins 企业级客户
 * @author Administrator
 *
 */
@Service(value="enterpriseService") @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class EnterpriseServiceLogin  extends BaseService implements EnterpriseService{
	private static Logger log = LoggerFactory.getLogger(EnterpriseServiceLogin.class);
	@Autowired
	private SystemMasterServerRpcClient systemMasterServerRpcClient;
	@Autowired
	private OmsOperListDao operatorDaoImpl;
	@Autowired
	private OmsStationDao omsStationDao;
	@Autowired
	public StationService stationService;
	@Autowired
	private OmsChargerDao omsChargerDao;
	
	@Autowired
	@Qualifier("base")
	private BaseDao<OmsStationLocation> baseDao;
	@Autowired
	@Qualifier("base")
	private BaseDao<OmsOperList> baseOperListDao;
	
	@Autowired
	private AuthenService authenService;
	//authenService
	@SuppressWarnings("rawtypes")
	public JsonCommon<?> thirdPartLogin(String usename, String password) {
		LoginParam loginParam=new LoginParam();
		loginParam.setUserId(usename);
		loginParam.setPassword(password);
		loginParam.setLoginType(1);
		ApiResult result=authenService.login(loginParam);
		RPCLoginRes rpcLoginRes=(RPCLoginRes) result.getData();//企业用户信息
		if(result != null && result.getStatus()==0){//企业用户登录成功
			MasterQueryCardsParamVO queryCardsParamVO=new MasterQueryCardsParamVO();
			queryCardsParamVO.setUserId(rpcLoginRes.getUserId());
			MasterQueryCardsRetVO  masterQueryCardsRetVO  = systemMasterServerRpcClient.queryCards(queryCardsParamVO) ;
			if(masterQueryCardsRetVO!=null && 1 == masterQueryCardsRetVO.getIsSuccess()){
				OmsOperList user = new OmsOperList();
				user.setMs_manager_id(rpcLoginRes.getUserId());//TODO luoyp oper_id
				Date now = new Date();
				try 
				{
					OmsOperList	sysUser = operatorDaoImpl.findOneExample(user, null, null);
					if (sysUser==null)
					{
						user.setMs_manager_id(usename);// 主服务器id
						// 添加默认用户
						user.setAccount(usename);
						user.setCreate_time(now);
						user.setLast_time(now);
						user.setEntity_type(0);//归属类型
						user.setUser_type("2");//用户类型  企业用户
						user.setStatus(1);//状态  1为启用
						user.setCompany(rpcLoginRes.getUserName());//公司名
						user.setAuth_range(2);//操作权限0：所归属实体下所有站；1：特定站；2：所有站（只针对企业用户）'
						user.setAccount(usename);//账户
						user.setPassword(password);//密码
						user.setOper_name(usename);//名字
						user.setValid_flag(1);//有效
						user.setNotify_url(rpcLoginRes.getNotifyUrl());//回滚地址
						user.setOper_id("MS" + serialGenerater.generateSerialNo());//管理员id
						// user.setStatus(1);
						operatorDaoImpl.add(user);
					}else
					{
						if(StringUtil.isNotBlank(rpcLoginRes.getNotifyUrl())){
							sysUser.setNotify_url(rpcLoginRes.getNotifyUrl());
						}
						sysUser.setLast_time(now);
						operatorDaoImpl.update(sysUser);
					}
					Map<String, String> map = new HashMap<String, String>();
						if(result.getToken()!=null&&masterQueryCardsRetVO.getCardList()!=null && masterQueryCardsRetVO.getCardList().get(0)!=null ){
							String token =  result.getToken();
							map.put("token", token);
							map.put("userPayCard",masterQueryCardsRetVO.getCardList().get(0).getCardNo());
						}else {
							return this.buildError400JsonCommon();
						}
					return buildSuccessJsonCommon(map);
			}catch (Exception e){ 
				this.logError("login,find user error", e);
				return this.buildError400JsonCommon();
			}
			
			}else{
				JsonCommon json=new JsonCommon();
				json.setCode(MsgCodeEnum.ERROR400.getMsgCode());
				json.setMsg("该用户没有卡号，请联系管理员生成卡号");
				return json;
			}
		}
			return buildError400JsonCommon();
		
		
	}

		//查询站点信息
		@SuppressWarnings("rawtypes")
		@Override
		public JsonForList getStationListByPage(OmsStationVO station, int pageNo, int pageSize, String sortName,
				int sortVal, String oper_id) {
				return omsStationDao.getStationListByPage(station.getStation(), pageNo, pageSize, sortName, sortVal, oper_id);
		}
		/**
		 * 
		 */
		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Override
		public JsonForList<?> getStationByPlantId(String station_id) {
			String sql = "SELECT b.*,c.*,d.* from oms_station a LEFT JOIN oms_charger b on a.station_id=b.station_id LEFT JOIN "+
					"oms_charger_state_alternate c on b.charger_id=c.charger_id LEFT JOIN "
					+ "oms_charger_state_direct d on b.charger_id=d.charger_id where a.station_id='"+station_id+"'"
					+ " and b.valid_flag=1 and b.is_allow_open=1";
					
		List<Map<String,Object>> retListMap = this.omsChargerDao.findDataBySql(sql, null);
		JsonForList json=new JsonForList<>();
		if(retListMap.size()!=0){
			json.setList(retListMap);
			json.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
			json.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
			
		}else{
			json.setCode(MsgCodeEnum.ERROR400.getMsgCode());
			json.setMsg(MsgCodeEnum.ERROR400.getMsgInfo());
		}
			return json;
		}
		@SuppressWarnings("rawtypes")
		@Override
		public JsonForList getStationList(OmsStation station, Integer pageNo,Integer pageSize,String sortName,Integer sortVal,String groupByStrs) {
			JsonForList<OmsStation> retJsons = new JsonForList<OmsStation>();
			List<OmsStation> list=omsStationDao.findListByCondition(station, "where valid_flag=1");
			if(list.size()<pageSize){
				pageNo=0;
				pageSize=list.size();
			}
			retJsons.setList(omsStationDao.findListByPageAndGroupAndOrderAndCondition(station, "where valid_flag=1",pageNo,pageSize,sortName,sortVal,groupByStrs));
			retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
			retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
			return retJsons;
		}
		@Override
		public List<OmsStationLocation> findByStationId(String id, Integer pageNo, Integer pageSize, String sortName,
				Integer sortVal) {
			try 
			{
				OmsStationLocation queryLocation = new OmsStationLocation();
				queryLocation.setStation_id(id);
				List<OmsStationLocation> lsStationLoc = baseDao.findExample(queryLocation, pageNo, pageSize, sortName, 1);
				return lsStationLoc;
			} 
			catch (Exception e) 
			{
				this.logError(e.getMessage(), e);
				return null;
			}
		}
		@SuppressWarnings({ "rawtypes", "unchecked" })
		@Override
		public JsonForList getCharsByStationId(String station_id) {
			OmsCharger station=new OmsCharger();
			JsonForList<OmsCharger> retJsons = new JsonForList<>();
			List list=omsChargerDao.findListByCondition(station, "where station_id='"+station_id+"' and valid_flag=1");
			if(list.size()!=0){
				retJsons.setList(list);
				retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
				retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
			}else{
				retJsons.setCode(MsgCodeEnum.ERROR400.getMsgCode());
				retJsons.setMsg(MsgCodeEnum.ERROR400.getMsgInfo());
			}
			return retJsons;
		}

		@Override
		public JsonCommon<?> splogin(String account, String password) {
		
			return null;
		}
		
		
}
